package com.cdwh.joylife.ui.base;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.afollestad.materialdialogs.MaterialDialog;

import com.cdwh.joylife.R;
import com.cdwh.joylife.bean.response.BaseResponse;
import com.cdwh.joylife.presenter.PresenterImpl;
import com.cdwh.joylife.presenter.ViewInterface;
import com.cdwh.joylife.utils.AppToast;
import com.cdwh.joylife.utils.Constants;
import com.cdwh.joylife.utils.ImageUtils;
import com.cdwh.joylife.utils.UiUtils;
import com.google.gson.Gson;
import com.omadahealth.github.swipyrefreshlayout.library.SwipyRefreshLayout;
import com.omadahealth.github.swipyrefreshlayout.library.SwipyRefreshLayoutDirection;
import com.socks.library.KLog;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;


import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.functions.Consumer;
import me.iwf.photopicker.PhotoPicker;
import me.iwf.photopicker.PhotoPreview;
import retrofit2.adapter.rxjava2.HttpException;
import timber.log.Timber;


/**
 * Created by admin on 2017/6/19.
 */

public abstract class BaseFragment extends Fragment implements ViewInterface {
    private static final int SETTINGS_REQUEST_CODE = 6;
    protected PresenterImpl presenter;

    private Unbinder unbinder;
    private View layoutView;
    protected MaterialDialog dialog;
    protected int page = 1;
    private SwipyRefreshLayout swipyRefreshLayout;
    protected boolean isLoadFinished = false;
    protected Map<String, Object> params;
    protected RxPermissions rxPermissions;
    private boolean isCreate = false;

    protected abstract int getLayoutResId();

    protected abstract void initView(View layoutView);


    public void onInternet() {

    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Activity activity = (Activity) context;
        rxPermissions = new RxPermissions(activity);
    }

    protected void startPreview(ArrayList<String> mImages, int currentItem) {
        ArrayList<String> imageUrls = ImageUtils.getImageUrls(mImages);
        PhotoPreview.builder()
                .setPhotos(imageUrls)
                .setCurrentItem(currentItem)
                .start(getActivity());
    }

    protected void startPreview(List<String> mImages, int currentItem) {
        ArrayList<String> images = (ArrayList<String>) mImages;
        ArrayList<String> imageUrls = ImageUtils.getImageUrls(images);
        PhotoPreview.builder()
                .setPhotos(imageUrls)
                .setCurrentItem(currentItem)
                .start(getActivity());
    }

    protected void openPhoto(final ArrayList<String> selected, final int selectCount, final boolean showCamera, final boolean showGif) {
        rxPermissions
                .request(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)

                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean granted) throws Exception {
                        if (granted) { // Always true pre-M
                            // I can control the camera now
                            if (selected == null) {

                                PhotoPicker.builder()
                                        .setPhotoCount(selectCount)
                                        .setShowCamera(showCamera)
                                        .setShowGif(showGif)
                                        .setPreviewEnabled(true)
                                        .start(getActivity(), BaseFragment.this, PhotoPicker.REQUEST_CODE);
                            } else {

                                PhotoPicker.builder()
                                        .setPhotoCount(selectCount)
                                        .setShowCamera(showCamera)
                                        .setSelected(selected)
                                        .setShowGif(showGif)
                                        .setPreviewEnabled(true)
                                        .start(getActivity(), BaseFragment.this, PhotoPicker.REQUEST_CODE);
                            }
                        } else {
                            // Oups permission denied
                            showPermissionsDialog();
                        }
                    }
                });
    }

    protected void showPermissionsDialog() {
        new AlertDialog.Builder(getActivity())
                .setTitle(getString(R.string.__picker_title_settings_dialog))
                .setMessage(getString(R.string.__picker_rationale_ask_again))
                .setPositiveButton(getString(R.string.__picker_setting), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null);
                        intent.setData(uri);
//            // Start for result

                        startActivityForResult(intent, SETTINGS_REQUEST_CODE);
//                          startForResult(activityOrFragment, intent, settingsRequestCode);
                    }
                })
                .setNegativeButton(getString(me.iwf.photopicker.R.string.__picker_cancel), null)
                .show();
    }

    @Override
    public void onError(Throwable throwable, int type) {
//        disRefresh();
//        if (throwable.getClass().equals(HttpException.class)) {
//            HttpException exception = (HttpException) throwable;
//            try {
//                String errorMsg = exception.response().errorBody().string();
//                BaseResponse response = new Gson().fromJson(errorMsg, BaseResponse.class);
//                String message = response.getMessage();
//                if (message.equals("权限验证不通过")) {
//                    AppToast.makeToast(getActivity(), "登录失效，请重新登录");
//                    SPUtils.clear();
//                    App.getActivityManager().finishAll();
//                    Intent intent = new Intent(getActivity(), LoginActivity.class);
//                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                    startActivity(intent);
//                } else {
//                    AppToast.makeToast(getActivity(), message);
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//
//
//        } else {
//            if (throwable.getClass().equals(UnknownHostException.class)) {
//                AppToast.makeToast("没有网络！");
//            } else if (throwable.getClass().equals(SocketTimeoutException.class)) {
//                AppToast.makeToast("网络繁忙,请稍后再试~");
//            } else if (throwable.getClass().equals(NullPointerException.class)) {
//                Timber.d("空指针异常");
//            } else if (throwable.getClass().equals(ConnectException.class)) {
//                AppToast.makeToast("没有网络哦，亲~");
//            } else if (throwable.getClass().equals(IllegalStateException.class)) {
////            JsonSyntaxException
////                Timber.d("");
//                AppToast.makeToast("对不起，对于您的请求，服务器处理失败了，我们会尽快修复。");
//            } else {
//                Timber.d("未知网络错误");
//                AppToast.makeToast("未知网络错误");
//            }
//        }
//        KLog.e("message" + throwable.getMessage());
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        presenter = new PresenterImpl(getActivity(), this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (layoutView == null) {
            layoutView = inflater.inflate(getLayoutResId(), container, false);
            unbinder = ButterKnife.bind(this, layoutView);
            params = new HashMap<>();
            params.put("pageSize", Constants.APP.PAGE_SIZE);
            initView(layoutView);
        } else {
            unbinder = ButterKnife.bind(this, layoutView);
        }

        if (container != null) {
            container.removeView(layoutView);
        }
        return layoutView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        onInternet();
        SwipyRefreshLayout refreshView = (SwipyRefreshLayout) view.findViewById(R.id.swipyRefreshLayout);
        if (refreshView != null) {
            if (!isCreate) {
                initRefresh(refreshView);
                KLog.e("初始化：onViewCreated");
            }
        }
    }


    protected void initRefresh(final SwipyRefreshLayout swipyRefreshLayout) {
        if (swipyRefreshLayout != null) {
            if (params == null) {
                params = new HashMap<>();
                params.put("pageSize", Constants.APP.PAGE_SIZE);
            }
            this.swipyRefreshLayout = swipyRefreshLayout;
            swipyRefreshLayout.setColorSchemeColors(Color.GREEN, Color.CYAN, Color.RED, Color.BLUE);
            final SwipyRefreshLayout.OnRefreshListener onRefreshListener = new SwipyRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh(SwipyRefreshLayoutDirection direction) {
                    KLog.e("MainActivity", "Refresh triggered at "
                            + (direction == SwipyRefreshLayoutDirection.TOP ? "top" : "bottom"));
                    KLog.d("MainActivity", direction + "--------");

                    swipyRefreshLayout.setDirection(SwipyRefreshLayoutDirection.BOTH);
                    boolean userVisibleHint = getUserVisibleHint();
                    if (userVisibleHint) {
                        if (direction == SwipyRefreshLayoutDirection.TOP) {
                            page = 1;
                            isLoadFinished = false;
                            params.put("page", page);
                            loadData(page);
                            //下拉刷新

//                    Toast.makeText(ContactsActivity.this, "刷新", Toast.LENGTH_SHORT).show();
                        } else {
                            if (isLoadFinished) {
                                AppToast.makeToast("已加载完毕");
                                disRefresh();
                                return;
                            }
                            page++;
                            params.put("page", page);
                            loadData(page);
//                    Toast.makeText(ContactsActivity.this, "下拉加载", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        KLog.e("页面不可见" + getClass().getName());
//                        disRefresh();
//                        params.clear();
//                        params = null;
                    }
                }
            };
            swipyRefreshLayout.setOnRefreshListener(onRefreshListener);
            swipyRefreshLayout.post(new Runnable() {
                @Override
                public void run() {
                    onRefreshListener.onRefresh(SwipyRefreshLayoutDirection.TOP);
                    swipyRefreshLayout.setRefreshing(true);
                }
            });
        }
    }

    protected abstract void loadData(int page);


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        KLog.e("-----" + getClass().getName());
        if (params != null) {
            params.clear();
            params = null;
        }

        unbinder.unbind();
    }

    public void gotoActivity(Class<?> clz) {
        gotoActivity(clz, false, null);
    }

    public void gotoActivity(Class<?> clz, boolean isClose) {
        gotoActivity(clz, isClose, null);
    }

    public void gotoActivity(Class<?> clz, boolean isClose, Bundle extras) {
        Intent intent = new Intent(getActivity(), clz);
        if (extras != null) {
            intent.putExtras(extras);
        }
        startActivity(intent);
        if (isClose) {
            getActivity().finish();
        }
    }

    @Override
    public void showDialog(String msg, boolean cancelable) {
        if (dialog == null) {
            dialog = new MaterialDialog.Builder(getActivity())
                    .content(msg)
                    .progress(true, 0).show();
        } else {
            dialog.setContent(msg);
            dialog.show();
        }
    }

    public void disDialog() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }


    protected void setLinearLayoutManagerVertical(RecyclerView recyclerView) {

        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
    }

    protected void setLinearLayoutManagerHorizontal(RecyclerView recyclerView) {

        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(manager);
    }

    protected void addItemDecoration(RecyclerView recyclerView) {
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration
                .Builder(getActivity()).color(UiUtils.getColor(R.color.color_dedede)).build());
    }

    protected void addItemDecoration(RecyclerView recyclerView, int leftMargin, int rightMargin) {
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration
                .Builder(getActivity()).color(UiUtils.getColor(R.color.color_dedede)).margin(leftMargin, rightMargin).build());
    }

    protected void setGridLayoutManager(RecyclerView recyclerView, int spanCount) {

        GridLayoutManager manager = new GridLayoutManager(getActivity(), spanCount);
        recyclerView.setLayoutManager(manager);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        boolean userVisibleHint = getUserVisibleHint();
        if (userVisibleHint && swipyRefreshLayout != null) {
            initRefresh(swipyRefreshLayout);
            isCreate = true;
            KLog.e("初始化：setUserVisibleHint");
        } else {
            KLog.e("----------" + getClass().getName());
            disRefresh();
        }
    }

    protected void showRefresh() {
        if (swipyRefreshLayout != null && !swipyRefreshLayout.isRefreshing()) {
            swipyRefreshLayout.setRefreshing(true);
        }
    }


    protected void disRefresh() {
        if (swipyRefreshLayout != null && swipyRefreshLayout.isRefreshing()) {
            swipyRefreshLayout.setRefreshing(false);
        }
    }

    protected View getRootView() {
        return ((ViewGroup) getActivity().findViewById(android.R.id.content)).getChildAt(0);
    }
}
